package algorithm.leetcode;

public class NO34_在排序数组中查找元素的第一个和最后一个位置 {
    static class Solution {
        public int[] searchRange(int[] nums, int target) {
            if (nums == null || nums.length == 0) {
                return new int[]{-1, -1};
            }
            int left = findLeftBound(nums, target);
            int right = findRightBound(nums, target);
            return new int[]{left, right};
        }

        private int findLeftBound(int[] nums, int target) {
            int left = 0, right = nums.length - 1;
            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] >= target) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
            if (left < nums.length && nums[left] == target) {
                return left;
            }
            return -1;
        }

        private int findRightBound(int[] nums, int target) {
            int left = 0, right = nums.length - 1;

            while (left <= right) {
                int mid = left + (right - left) / 2;
                if (nums[mid] <= target) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
            if (right >= 0 && nums[right] == target) {
                return right;
            }
            return -1;
        }
    }
}
